<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-alert title="添加商品信息" :closable="false" type="info" center show-icon></el-alert>

      <!-- 步骤条 -->

      <el-steps :space="200" :active="+activeIndex" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 标签页 -->

      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabIndex"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="活动名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <template slot-scope="scope">
                <el-cascader
                  v-model="addForm.goods_cat"
                  :props="cateProps"
                  :options="cateList"
                  @change="handleChange"
                ></el-cascader>
              </template>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyTabData" :label="item.attr_name" :key="item.id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" border v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- active图片上传的api地址 -->
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headerObj"
              list-type="picture"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor"></quill-editor>

            <el-button type="primary" class="add-btn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 图片预览 -->
      <el-dialog title="预览" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
        <img :src="previewImg" alt />
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import _ from "lodash";
export default {
  data() {
    return {
      activeIndex: 0,
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur"
          }
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur"
          }
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur"
          }
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur"
          }
        ],
        goods_cat: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "blur"
          }
        ]
      }, //表单验证规则
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: "",
        // 商品图片
        pics: [],
        // 商品详情
        goods_introduce: "",
        attrs: []
      },
      cateList: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      manyTabData: [], //动态页面参数获取
      onlyTabData: [],
      //   图片上传请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      previewImg: "", //预览展示图片
      dialogVisible: false
    };
  },
  created() {
    this.getCateList();
  },

  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      } else {
        return false;
      }
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      this.$message.success("获取商品成功！");
      this.cateList = res.data;
    },
    // 级联选择器选中触发这个函数
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    // 没有填写参数禁止切换面板
    beforeTabLeave(active, oldActive) {
      console.log("即将离开的标签" + oldActive);
      if (oldActive === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品");
        return false;
      }
    },
    // 点击面板
    async tabIndex() {
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (res.meta.status !== 200) return this.$message.error("获取数据失败");
        this.$message.success("获取数据成功！");

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(",");
        });

        this.manyTabData = res.data;
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        if (res.meta.status !== 200) return this.$message.error("获取数据失败");
        this.$message.success("获取数据成功！");
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(",");
        });

        this.onlyTabData = res.data;
      }
    },
    // 处理图片预览
    handlePreview(file) {
      this.previewImg = file.response.data.url;
      this.dialogVisible = true;
    },
    // 处理删除图片
    handleRemove() {},
    handleSuccess(res) {
      const picInfo = {
        pic: res.data.tmp_path
      };
      this.addForm.pics.push(picInfo);
      console.log(res);
    },
    // 删除图片
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      const i = this.addForm.pics.findIndex(x => x.pic === filePath);
      this.addForm.pics.splice(i, 1);
    },
    handleClose() {
      this.dialogVisible = false;
    },
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项");
        }
        // 添加商品

        // lodsh cloneDeep()  深拷贝 将数组转换成字符串
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");

        // 处理动态参数 和
        this.manyTabData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          };
          this.addForm.attrs.push(newInfo);
        });
        // 静态属性
        this.onlyTabData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          };
          this.addForm.attrs.push(newInfo);
        });

        form.attrs = this.addForm.attrs;
        console.log(form, "2323");

        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status !== 201)
          return this.$message.error("获取商品分类失败");
        this.$message.success("获取商品成功！");
        this.$router.push("/goods");
      });
    },
    // 富文本里面的方法
    onEditorReady(e) {
      console.log(e);
    }
  }
};
</script>

<style scoped>
.el-steps {
  margin: 15px 0;
}
.add-btn {
  margin-top: 15px;
}
</style>